package com.ljx.itbbs.server.mall.consumer;

import com.ljx.itbbs.server.mall.domain.entity.CouponRecordEntity;
import com.ljx.itbbs.server.mall.service.CouponRecordService;
import com.ljx.itbbs.server.mall.service.CouponService;
import com.ljx.itbbs.server.mall.service.adapter.CouponAdapter;
import com.ljx.itbbs.server.mq.domain.mall.CouponMsgDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description: 优惠券订单消费者
 * @Date: 2024-03-31  09:52
 */
@Slf4j
@Component
public class CouponConsumer {

    @Autowired
    private CouponRecordService couponRecordService;

    @Lazy
    @Autowired
    private CouponService couponService;

    public static final String COUPON_EXCHANGE = "itbbs.coupon.exchange";
    public static final String COUPON_QUEUE = "itbbs.coupon.queue";
    public static final String COUPON_KEY = "coupon";

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = COUPON_QUEUE, durable = "true"),
            exchange = @Exchange(name = COUPON_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = COUPON_KEY
    ))
    public void listenQueue(CouponMsgDto msgDto) {
            Long userId = msgDto.getUserId(), couponId = msgDto.getCouponId();
            // 检查是否已经领取
            CouponRecordEntity couponRecord = couponRecordService.getCouponRecord(userId, couponId);
            if (Objects.nonNull(couponRecord)){
                return;
            }
            // 扣减库
            couponService.reduceStock(couponId);
            // 保存领取记录
            couponRecordService.saveCouponRecord(CouponAdapter.buildCouponRecordSave(userId, couponId));
    }
}

